package cn.piumnl.tool.mapeditor;

import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Scanner;

import javafx.event.EventHandler;
import javafx.scene.Node;
import javafx.scene.canvas.Canvas;
import javafx.scene.canvas.GraphicsContext;
import javafx.scene.control.Alert;
import javafx.scene.image.Image;
import javafx.scene.input.MouseEvent;
import javafx.scene.paint.Color;

/**
 * @author piumnl
 * @version 1.0.0
 * @since on 2017-06-02.
 */
public class MapConfig implements EventHandler<MouseEvent> {

    private int cellWidth;
    private Image image;
    private int[][] map;
    private Canvas canvas;
    private GraphicsContext gc;

    public MapConfig() {
        this(32);
    }

    public MapConfig(int cellWidth) {
        this.cellWidth = cellWidth;
    }

    /**
     * 加载图片，创建一个画布，为画布设置鼠标点击事件，并将图片绘制出来
     * @param image 所要加载的图片
     * @return 返回创建的画布
     */
    public Node loadImg(Image image) {
        this.image = image;
        int col = (int) (image.getWidth() / cellWidth);
        int row = (int) (image.getHeight() / cellWidth);
        map = new int[row][col];

        if (canvas != null) {
            canvas.setOnMouseClicked(null);
        }

        canvas = new Canvas(image.getWidth(), image.getHeight());
        canvas.setOnMouseClicked(this);
        gc = canvas.getGraphicsContext2D();
        gc.drawImage(image, 0, 0);

        return canvas;
    }

    @Override
    public void handle(MouseEvent event) {
        double sceneX = event.getX();
        double sceneY = event.getY();

        if (sceneX <= image.getWidth() && sceneY <= image.getHeight()) {
            int x = (int) (sceneX / cellWidth);
            int y = (int) (sceneY / cellWidth);
            map[y][x] = (map[y][x] + 1) % 2;
        }

        repaint();
    }

    /**
     * 加载地图文件，并将地图渲染到图片中，使用红色矩形框飘红不可走的路
     * @param file
     * @throws IOException
     */
    public void loadMap(File file) throws IOException {
        int y = 0;

        Scanner scanner = new Scanner(file);
        while (scanner.hasNextLine()) {
            String s = scanner.nextLine();
            if (s != null && !"".equals(s)) {
                String[] split = s.split(", *+");
                if (split.length != this.map[0].length) {
                    alertNoMatch("检测到图片与地图文件不匹配，\n请重新选择图片或地图文件");
                    return;
                }
                for (int i = 0; i < split.length; i++) {
                    map[y][i] = Integer.parseInt(split[i]);
                }
            }
            y++;
        }

        if (y != this.map.length) {
            alertNoMatch("检测到图片与地图文件不匹配，\n请重新选择图片或地图文件");
            return;
        }
        repaint();
    }

    /**
     * 对整个图片及地图文件进行绘制
     */
    private void repaint() {
        gc.clearRect(0, 0, image.getWidth(), image.getHeight());
        gc.drawImage(image, 0, 0);
        gc.setStroke(Color.RED);
        for (int i = 0; i < map.length; i++) {
            for (int j = 0; j < map[i].length; j++) {
                if(map[i][j] < 1)
                    continue;
                gc.strokeRect(j * cellWidth, i * cellWidth, cellWidth, cellWidth);
            }
        }
    }

    public void alertNoMatch(String contentText) {
        Alert alert = new Alert(Alert.AlertType.INFORMATION);
        alert.setTitle("提示");
        alert.setHeaderText("");
        alert.setContentText(contentText);
        alert.showAndWait();
    }

    public void save(File file) throws IOException {
        try (PrintWriter writer = new PrintWriter(file)) {
            for (int[] ints : map) {
                int length = ints.length - 1;
                StringBuilder builder = new StringBuilder();
                for (int j = 0; j < length; j++) {
                    builder.append(ints[j]).append(",");
                }
                builder.append(ints[ints.length - 1]);
                writer.println(builder);
            }
            writer.flush();
        }
    }

    public boolean hasLoadImage() {
        return image != null;
    }
}
